<template>
  <div class="qrcode-wapper">
    <!-- 二维码预览 -->

    <qrcode
      class="q-r-code"
      :id="cv"
      :value="allAccessUrl"
      :options="{ size: optionSize }"/>
    <el-upload
      ref="upload"
      v-show="logoShow"
      :action="uploadUrl"
      :data="uploadData"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-progress="handleProgress"
      :file-list="fileList"
      v-bind="{...(isUseQiniu ? {'before-upload':beforeUpload} : {'http-request': onUpload, 'before-upload': cosBeforeUpload})}"
      accept=".png, .jpg, .jpeg, .gif">
      <a
        class="el-upload__button"
        v-show="loading !== -1">
        {{loadingTip}}
      </a>
      <div
        v-show="loading !== -1"
        slot="tip"
        class="el-upload__tip">
        {{$t('configLazyLoad.channel.dockingError16')}}
      </div>
    </el-upload>
  </div>
</template>

<script>
  import qrcode from '@xkeshi/vue-qrcode'
  import { qiniuUploadUrl, qiniu7moorDomain } from '@utils/qiniuUtils'
  import { getCurrentDate, deepClone } from '@utils/m7Utils'
  import { common } from '@/utils/cosUrl'
  import * as uuid from 'uuid'
  import { uploadQRcode } from '@/utils/qiniuUtils'
  export default {
    name: 'QrcodeImage',
    data () {
      return {
        loading: 0,
        url: '',
        uploadUrl: qiniuUploadUrl || '',
        uploadData: {},
        logoUrl: '',
        dialogVisible: false,
        fileList: [],
        isUseQiniu: this.$store.state.isUseQiniu
      }
    },
    props: {
      layout: {
        type: String,
        default: 'inline'
      },
      logoShow: {
        type: Boolean,
        default: true
      },
      optionSize: {
        type: Number,
        default: 200
      },
      initLogo: {
        type: Object,
        default: () => {
          return {
            name: '',
            url: ''
          }
        }
      },
      isQRcode: Boolean,
      allAccessUrl: String
    },
    watch: {
      allAccessUrl () {
        this.loading = 0
      },
      initLogo (n, o) {
        if (!n.id) {
          this.uploadFile = {}
          this.fileList = []
          this.logoUrl = ''
        } else {
          this.uploadFile = {}
          this.fileList = []
          this.logoUrl = common.getUrl(n)
          this.load(this.logoUrl)
          this.uploadFile = {...deepClone(n)}
          this.fileList.push({url: this.logoUrl, ...deepClone(n)})
        }
      }
    },
    computed: {
      loadingTip () {
        let loading = this.loading
        if (loading === 0) {
          return this.$t('configLazyLoad.channel.injectImg')
        } else if (loading === 1) {
          return this.$t('configLazyLoad.channel.injectImgIng')
        }
      },
      cv () {
        return `cv${uuid.v1()}`
      },
      cmpDomain () {
        return this.isUseQiniu ? '' : this.$store.state.fileDomain.cos7moorCommonDomain
      },
    },
    methods: {
      generateUploadResourceKey (store, name) {
        let date = getCurrentDate()
        let today = new Date()
        let time = today.getTime()
        let key = '/' + store.state.session.user.account + '/customer/' + date + '/' + time + '/' +uuid.v1() + name
        return key
      },
      // 重置二位码相关字段
      restFileList () {
        this.$set(this, 'fileList', [])
        this.logoUrl = ''
        if (!this.initLogo.id) return
        this.logoUrl = common.getUrl(this.initLogo)
        this.fileList.push({url: this.logoUrl, ...deepClone(this.initLogo)})
      },

      // 将二维码生成图片
      downQRcode () {
        let mycv = document.getElementById(this.cv)
        return mycv.toDataURL('image/png')
      },

      // 将logo嵌入二维码
      drawBeauty (beauty) {
        if (this.cv) {
          let mycv = document.getElementById(this.cv)
          let myctx = mycv.getContext('2d')
          myctx.drawImage(beauty, 80, 80, 40, 40)
          beauty = null
        }
      },
      load (url) {
        let beauty = document.createElement('img')
        let that = this
        let flag = true
        beauty.onload = function () {
          let canvas = document.createElement('canvas')
          let ctx = canvas.getContext('2d')
          if (flag) {
            flag = false
            canvas.height = beauty.height
            canvas.width = beauty.width
            ctx.drawImage(beauty, 0, 0)
            let dataURL = canvas.toDataURL('image/png')
            canvas = null
            if (dataURL) {
              beauty.src = dataURL
              that.drawBeauty(beauty)
            }
          }
        }
        beauty.crossOrigin = 'Anonymous'
        beauty.src = url
      },
      // 将logo嵌入二维码 end

      // 上传中...
      handleProgress () {
        this.loading = 1
      },

      // 移除上传的文件
      handleRemove (file, fileList) {
        this.$set(this, 'fileList', [])
        this.logoUrl = ''
        this.uploadFile = {}
        this.loading = 0
      },

      //  预览
      handlePreview (file) {
        this.dialogVisible = true
      },

      // 上传成功...
      // handleSuccess (response, file, fileList) {
      handleSuccess (response, originFile) {
        // if (!this.isUseQiniu && this.$refs.upload.uploadFiles.length > 0) {
        //   this.$refs.upload.uploadFiles = 
        //     this.$refs.upload.uploadFiles.map(i => !i.isNew ? ({...i, name: response.fileKey}): i)
        // }
        this.loading = 1
        const file = this.isUseQiniu ? originFile : this.file
        let fileUrl = this.isUseQiniu ? response.key : response.fileKey
        if (!fileUrl) {
          return
        }
        const domain = this.isUseQiniu ? qiniu7moorDomain : ''
        let trueName = file.name
        let uploadFile = { id: fileUrl, name: file.name, type: 'other', isNew: 1 }
        let imgTypes = ['jpg', 'jpeg', 'gif', 'png']
        let suffix = trueName.substring(trueName.lastIndexOf('.') + 1)
        suffix = suffix.toLowerCase()
        if (imgTypes.indexOf(suffix) !== -1) {
          uploadFile.type = 'img'
        }
        this.logoUrl = `${domain}${fileUrl}?imageView2/1/w/50`
        this.fileList = []
        this.fileList.push({url: this.logoUrl, ...uploadFile})
        this.uploadFile = {...uploadFile}
        this.loading = -1
        this.load(this.logoUrl)
        this.$emit('logo-upload-success')
      },
      async onUpload (info) {
        const { file } = info
        this.file = file
        if (file.size > 1024 * 1024) {
          this.$message.error(this.$t('configLazyLoad.channel.dockingError17'))
          return false
        }
        uploadQRcode(file, file.name, this.handleProgress, this.handleSuccess, this.generateUploadResourceKey(this.$store, file.name), null, this.cmpDomain)
        return true
      },
      cosBeforeUpload (file) {
        if (file.size > 1024 * 1024) {
          this.$message.error(this.$t('configLazyLoad.channel.dockingError17'))
          return false
        }
      },
      // 上传前预览 和 判断
      beforeUpload (file) {
        this.loading = 1
        this.$emit('logo-upload-loading')
        if (file.size > 1024 * 1024) {
          this.$message.error(this.$t('configLazyLoad.channel.dockingError17'))
          this.loading = -1
          this.$emit('logo-upload-outsize')
          return false
        }
        let key = this.generateUploadResourceKey(this.$store)
        // let key = this.beforeUploadgenerateUploadResourceKey(this.$store)
        return this.$store.dispatch('getImTestQiniuToken', {key}).then(response => {
          this.putUrl = response.putUrl
          if (response.uptoken) {
            this.uploadData.token = response.uptoken
          }
          this.uploadData.key = key
        })
      }
    },
    components: {
      qrcode
    },
    beforeMount () {
      this.loading = 0
      if (!this.initLogo.id) return
      this.fileList = []
      this.uploadFile = {}
      this.logoUrl = common.getUrl(this.initLogo)
      this.load(this.logoUrl)
      this.fileList.push({url: this.logoUrl, ...deepClone(this.initLogo)})
      this.uploadFile = {...deepClone(this.initLogo)}
    },
    updated () {
//      this.load('//')
      if (!this.isQRcode && !this.logoUrl) return
      this.load(this.logoUrl)
    }
  }
</script>

<style lang="stylus" scoped>
  .qrcode-wapper
    display flex
    .q-r-code
      margin-right 24px
  .el-upload__button
    font-size 14px
</style>
